//
//  VillageAffairsManageTableVC.m
//  Cunli
//
//  Created by ZhanyaaLi on 15/11/2.
//  Copyright © 2015年 lilubin. All rights reserved.
//

#import "VillageAffairsManageTableVC.h"
#import "SettingTableViewCell.h"
#import "Config.h"
#import "ContentViewCell.h"
#import "ZYQAssetPickerController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "UIViewExt.h"
#import "HGPhotoWall.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIImage+fixOrientation.h"
#import "Utils.h"
#import "MWPhotoBrowser.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kTitle @"affairsTitle"
#define kContent @"affirsContent"
#define kObject @"affarisObject"
#define kOrganization @"affairsOrganization"
#define kDate @"affairsDate"
#define imgViewTag 300
#define closeBtnTag 500
//#define PICBASEURL @"http://121.41.117.249"
#define PICBASEURL @"http://cunli.zhanyaa.com"

static NSString *kSettingCellID = @"SettingTableViewCell";

@interface VillageAffairsManageTableVC () <UITableViewDelegate, UITableViewDataSource,ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,HGPhotoWallDelegate, UIActionSheetDelegate,UIImagePickerControllerDelegate, UITextFieldDelegate, UITextViewDelegate, UIScrollViewDelegate, MWPhotoBrowserDelegate>
{
    NSMutableArray *imgDataArray;  //存储将要上传的图片的数据
    NSInteger lastArrayCount;
    UIView *_photoView;
    NSInteger keyPosition, textFieldPosition;
    UIDatePicker *_publishDatePicker;
    NSMutableString *picsUrlString;
    NSMutableDictionary *_affairsDic;
//    ZYQAssetPickerController *_photoPicker;
}

@property (nonatomic, strong) HGPhotoWall *photoWall;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *photos;


@end

@implementation VillageAffairsManageTableVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initAllGlobalParams];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self createNavBtn];
    [self initPublishDatePicker];
    [self initZYTableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

- (void)initAllGlobalParams
{
    imgDataArray = [NSMutableArray arrayWithCapacity:1];
    _photos = [NSMutableArray array];
    NSDate *senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    _affairsDic = [NSMutableDictionary dictionaryWithDictionary:@{kTitle:@"", kContent:@"", kObject:@"全体村民", kOrganization:[NSString stringWithFormat:@"%@村委", [Config getVillageName]], kDate:locationString}];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initPublishDatePicker
{
    _publishDatePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 220)];
    _publishDatePicker.backgroundColor=[UIColor whiteColor];
    _publishDatePicker.datePickerMode=UIDatePickerModeDateAndTime;
    _publishDatePicker.date=[NSDate date];
    [_publishDatePicker addTarget:self action:@selector(choose:) forControlEvents:UIControlEventValueChanged];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

/*
- (void)initAssetPickerController
{
    _photoPicker = [[ZYQAssetPickerController alloc] init];
    //    picker.maximumNumberOfSelection = 10-_oldImageURLArrays.count-imgDataArray.count;
    _photoPicker.maximumNumberOfSelection = 12;
    NSLog(@"--还可以选择---:%ld", (long)_photoPicker.maximumNumberOfSelection);
    _photoPicker.assetsFilter = [ALAssetsFilter allPhotos];
    _photoPicker.showEmptyGroups=NO;
    _photoPicker.delegate=self;
    _photoPicker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
}
 */

- (void)createNavBtn
{
    self.title=@"村务公开发布";
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 65, 30);
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(publishThings) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIBarButtonItem *flexSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpacer.width = flexSpacer.width - 20;
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer, rightBarItem, nil]];
}

-(void)choose:(UIDatePicker *)pick{

    SettingTableViewCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:8 inSection:0]];
    NSDateFormatter *format=[[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm"];
    cell.textField.text=[NSString stringWithFormat:@"%@",[format stringFromDate:pick.date]];
    if (cell.textField.text.length != 0) {
        [_affairsDic setObject:[NSString stringWithFormat:@"%@",[format stringFromDate:pick.date]] forKey:kDate];
    }
}

- (void)initZYTableView
{
    CGRect rect = self.view.bounds;
    rect.size.height = rect.size.height-64;
    _tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
    [self.view addSubview:_tableView];
    
    NSInteger picWidth=(kScreenWidth-70)/4.0;
    _photoView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, kScreenWidth, picWidth+15)];
    _photoView.backgroundColor = [UIColor colorWithHexString:UIBgColorValue];
    self.photoWall = [[HGPhotoWall alloc] initWithFrame:CGRectMake(0, 0, 0, 0) andLayoutPhotoType:LayoutTwelfPhotos];
    self.photoWall.backgroundColor = [UIColor colorWithHexString:UIBgColorValue];
    [self.photoWall setPhotos:nil];
    self.photoWall.delegate = self;
    [self.photoWall setEditModel:YES];
    [_photoView addSubview:_photoWall];
    _photoView.userInteractionEnabled = YES;
    _photoView.clipsToBounds = YES;
    _photoView.tag = 1500;

}

#pragma mark - UITableViewDelegate&UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SettingTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:kSettingCellID owner:self options:nil].lastObject;
    UIColor *bgColor = [UIColor colorWithHexString:UIBgColorValue];
    cell.backgroundColor = bgColor;
    cell.textField.textAlignment = NSTextAlignmentLeft;
    cell.textField.layer.borderColor = [UIColor colorWithHexString:TextViewBorderColorValue].CGColor;
    cell.textField.layer.borderWidth = 0.5;
    [cell.titleLabel setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
//    cell.textField.layer.cornerRadius = 5;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    /*
    if (indexPath.row == 0) {
        UITableViewCell *cell0 = [[UITableViewCell alloc] init];
        cell0.textLabel.text = @"标 题";
        cell0.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell0;
    }
    else 
    */
    if(indexPath.row == 0) //村务公开标题输入框
    { 
        UITableViewCell *cell1 = [[UITableViewCell alloc] init];
        UITextField *titleTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, kScreenWidth-20, 40)];
        titleTextField.tag = 1501;
        titleTextField.delegate = self;
        [titleTextField setFont:[UIFont systemFontOfSize:15]];
        [cell1.contentView addSubview:titleTextField];
        titleTextField.textAlignment = NSTextAlignmentLeft;
        [titleTextField setBackgroundColor:[UIColor whiteColor]];
        titleTextField.placeholder = @"村务公开标题";
        titleTextField.layer.borderColor = [UIColor colorWithHexString:TextViewBorderColorValue].CGColor;
        titleTextField.layer.borderWidth = 0.5;
        titleTextField.layer.cornerRadius = 2.0;
        [cell1 setBackgroundColor:bgColor];
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell1;
        
    }
    /*
    else if(indexPath.row == 1) //内容标签
    {
        UITableViewCell *cell2 = [[UITableViewCell alloc] init];
        cell2.textLabel.text = @"内 容";
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell2;
    }
    */
    else if(indexPath.row == 1) //内容输入UITextView
    {
        ContentViewCell *contentCell = [[NSBundle mainBundle] loadNibNamed:@"ContentViewCell" owner:self options:nil].lastObject;
        contentCell.textView.delegate = self;
//        [contentCell setBackgroundColor:bgColor];
        return contentCell;
    }
    else if(indexPath.row == 2) //照片选择cell
    {
        UITableViewCell *cellTemp = [UITableViewCell new];
        [cellTemp setBackgroundColor:bgColor];
        cellTemp.selectionStyle = UITableViewCellSelectionStyleNone;
        cellTemp.contentView.clipsToBounds = YES;
        UIView *oldPhotoView = [cellTemp.contentView viewWithTag:1500];
        if (oldPhotoView == nil) {
            [cellTemp.contentView addSubview:_photoView];
        }
        return cellTemp;
    }
    else if(indexPath.row == 3) //图片上传限制cell
    {
        UITableViewCell *cell5 = [[UITableViewCell alloc] init];
        cell5.textLabel.text = @"上传图片（最多上传12张）";
        cell5.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell5 setBackgroundColor:bgColor];
        [cell5.textLabel setTextColor:[UIColor colorWithHexString:InfoCellIntroduceColorValue]];
        return cell5;
    }
    else if(indexPath.row == 4)
    {
        cell.titleLabel.text = @"发布对象";
        cell.textField.placeholder = @"全体村民";
        cell.textField.delegate = self;
        cell.textField.tag = 1504;
        return cell;
    }
    else if(indexPath.row == 5)
    {
        cell.titleLabel.text = @"发布单位";
        cell.textField.placeholder = [NSString stringWithFormat:@"%@村委", [Config getVillageName]];
        cell.textField.delegate = self;
        cell.textField.tag = 1505;
        return cell;
    }
    else if(indexPath.row == 6)
    {
        cell.titleLabel.text = @"发布时间";
        NSDate *senddate=[NSDate date];
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *locationString=[dateformatter stringFromDate:senddate];
        cell.textField.placeholder = locationString;
        cell.textField.inputView = _publishDatePicker;
        cell.textField.delegate = self;
        cell.textField.tag = 1506;
        return cell;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) { //村务公开标题输入框高度
        return 70;
    }
    else if(indexPath.row == 3) //标题，内容等提示标签的高度
    {
        return 40;
    }
    else if(indexPath.row == 1) //内容输入UITextView的高度
    {
        return 110;
    }
    else if(indexPath.row == 2) //照片选择cell的高度
    {
        NSInteger picWidth=(kScreenWidth-70)/4.0;
        NSInteger picWidthAndBlock = picWidth+5;
        NSInteger photoRow = _photoWall.arrayPhotos.count/4;
        if (_photoWall.arrayPhotos.count < 14) {
            photoRow = photoRow+(_photoWall.arrayPhotos.count%4?1:0);
            if (_photoWall.arrayPhotos.count == 13) {
                photoRow = 3;
            }
            CGFloat photoWallHeight = photoRow*picWidthAndBlock+15;
            CGRect oldRect = _photoView.frame;
            oldRect.size.height = photoWallHeight;
            [_photoView setFrame:oldRect];
            return photoWallHeight;
        }
        return picWidthAndBlock*3+15;
    }
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2 || indexPath.row == 3) {
        [self resignTheKeyboard];
    }
}

- (void)reloadHeight
{
    NSIndexPath *zyIndexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[zyIndexPath] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - 键盘相关处理
- (void)resignTheKeyboard
{
//    NSLog(@"Resign keyboard");
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        _tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
    }];
}


-(void)textFieldDidBeginEditing:(UITextField *)textField{
    NSIndexPath *selIndexPath = [NSIndexPath indexPathForRow:(textField.tag-1500) inSection:0];
    CGRect rectInTableView = [_tableView rectForRowAtIndexPath:selIndexPath];
    CGPoint point = [_tableView convertPoint:rectInTableView.origin toView:self.view];
    textFieldPosition=point.y+rectInTableView.size.height+64;
    [self performSelector:@selector(delayMethod) withObject:nil afterDelay:0.5f];
    
    /*
    if ((textField.tag - 1500) == 1) {
        [_affairsDic setObject:textField.text forKey:kTitle];
    }
    else if ((textField.tag-1500) == 6) {
        if (textField.text.length != 0) {
            [_affairsDic setObject:textField.text forKey:kObject];
        }
    }
    else if((textField.tag - 1500) == 7)
    {
        if (textField.text.length != 0) {
            [_affairsDic setObject:textField.text forKey:kOrganization];
        }
    }
     */
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if ((textField.tag - 1500) == 1) {
        [_affairsDic setObject:textField.text forKey:kTitle];
    }
    else if ((textField.tag-1500) == 6) {
        if (textField.text.length != 0) {
            [_affairsDic setObject:textField.text forKey:kObject];
        }
    }
    else if((textField.tag - 1500) == 7)
    {
        if (textField.text.length != 0) {
            [_affairsDic setObject:textField.text forKey:kOrganization];
        }
    }
    return YES;
}



- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"对村务公开内容进行说明"]) {
        textView.text = @"";
    }
    [textView setTextColor:[UIColor blackColor]];
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    [_affairsDic setObject:textView.text forKey:kContent];
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    [_affairsDic setObject:textView.text forKey:kContent];
    return YES;
}

-(void)delayMethod{
    if (textFieldPosition>keyPosition) {
        [UIView animateWithDuration:0.5 animations:^{
            _tableView.frame = CGRectMake(0, (keyPosition-textFieldPosition), kScreenWidth, kScreenHeight-64);
        }];
    }
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    //键盘位置
    keyPosition = keyboardRect.origin.y;
}


-(void)addPics{
    
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 12 - self.photoWall.arrayPhotos.count+1;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups=NO;
    picker.delegate=self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
 
    [self presentViewController:picker animated:YES completion:NULL];
}

#pragma - mark HGPhoto Delegate
- (void)photoWallAddAction
{
    //    [self addPics];
    [self resignTheKeyboard];
    [[[UIActionSheet alloc] initWithTitle:@"添加图片"
                                 delegate:self
                        cancelButtonTitle:@"取消"
                   destructiveButtonTitle:nil
                        otherButtonTitles:@"拍照", @"从相册中选择", nil]
     
     showInView:self.view];
}

- (void)photoWallPhotoBrowser:(NSUInteger)index
{
    BOOL displayActionButton = YES;
    BOOL displaySelectionButtons = NO;
    BOOL displayNavArrows = NO;
    BOOL enableGrid = YES;
    BOOL startOnGrid = NO;
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = displayActionButton;
    browser.displayNavArrows = displayNavArrows;
    browser.displaySelectionButtons = displaySelectionButtons;
    browser.alwaysShowControls = displaySelectionButtons;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = enableGrid;
    browser.startOnGrid = startOnGrid;
    browser.enableSwipeToDismiss = NO;
    [browser setCurrentPhotoIndex:index];
    [browser showNextPhotoAnimated:YES];
    browser.isScrollerPic = YES;
    [browser showPreviousPhotoAnimated:YES];
    
    [self.navigationController pushViewController:browser animated:YES];
}

/*
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view.hidden = NO;
}
 */

#pragma mark - MWPhotoBrowser Delegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photos.count)
        return [_photos objectAtIndex:index];
    return nil;
}


- (void)photoWallPhotoTaped:(NSUInteger)index
{
    [imgDataArray removeObjectAtIndex:index];
    [self.photoWall deletePhotoByIndex:index];
    [self.photos removeObjectAtIndex:index];
    [self reloadHeight];
}

#pragma mark - ActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    } else if (buttonIndex == 1) {
        [self addPics];
    } else {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"警告"
                                                                message:@"无法访问摄像头"
                                                               delegate:nil
                                                      cancelButtonTitle:@"取消"
                                                      otherButtonTitles: nil];
            
            [alertView show];
        } else {
            UIImagePickerController *imagePickerController = [UIImagePickerController new];
            imagePickerController.delegate = self;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.allowsEditing = NO;
            imagePickerController.showsCameraControls = YES;
            imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
    }
}

#pragma mark - UIPickerViewDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
    UIImage *tempImg = info[UIImagePickerControllerOriginalImage];
    
    
    [self.photoWall addLocalPhoto:tempImg];
    MWPhoto *photo = [MWPhoto photoWithImage:tempImg];
    [self.photos addObject:photo];
    
    UIImage *tempImgOrientation = [tempImg fixOrientation];
    
    if (tempImgOrientation.size.width>1024 && tempImgOrientation.size.height>1024) {
        tempImgOrientation = [Utils sizeCompressImageTo1024With:tempImgOrientation];
    }
    
    
    NSData *data=UIImagePNGRepresentation(tempImgOrientation);
    //判断图片大小确定压缩比例
    if (data.length>1024*1024*2) {
        data=UIImageJPEGRepresentation(tempImgOrientation,0.2);
    }else{
        data=UIImageJPEGRepresentation(tempImgOrientation,0.5);
    }
    [imgDataArray addObject:data];
    [self reloadHeight];
}

#pragma - mark AssetPickerDelegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    //移除上次的图片
    for (int i=0; i<lastArrayCount+1; i++) {
        
        if (i==lastArrayCount) {
//            addPicBtn.frame=CGRectMake(1000, 10000, 70, 70);
            break;
        }
        UIImageView *img=(UIImageView *)[self.view viewWithTag:imgViewTag+i];
        [img removeFromSuperview];
    }
    
    lastArrayCount=assets.count;
    for (int i=0; i<assets.count; i++) {
        ALAsset *asset=assets[i];
        UIImage *tempImg=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        if (tempImg.size.width>1024 && tempImg.size.height>1024) {
            tempImg = [Utils sizeCompressImageTo1024With:tempImg];
        }
        [self.photoWall addLocalPhoto:tempImg];
        MWPhoto *photo = [MWPhoto photoWithImage:tempImg];
        [self.photos addObject:photo];
        
        NSData *data=UIImagePNGRepresentation(tempImg);
        //判断图片大小确定压缩比例
        if (data.length>1024*1024*2) {
            data=UIImageJPEGRepresentation(tempImg,0.2);
        }else{
            data=UIImageJPEGRepresentation(tempImg,0.5);
        }
        [imgDataArray addObject:data];
    }
    [self reloadHeight];
}

#pragma mark - 发布内容时的相关操作
-(void)publishThings{
    [self.view endEditing:YES];
    if ([[_affairsDic objectForKey:kTitle] isEqualToString:@""]) {
        [Config showHUDWithText:@"标题不能为空" andImage:@"error"];
    }else{
        if (imgDataArray.count==0) {
            [self sendContent];
        }else{
            [self uploadPics];
        }
    }
}

-(void)sendContent{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc] init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[_affairsDic objectForKey:kTitle] forKey:@"title"];
    [CheckParams setObject:[_affairsDic objectForKey:kContent]  forKey:@"content"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    [CheckParams setObject:[_affairsDic objectForKey:kObject] forKey:@"object"];
    [CheckParams setObject:[_affairsDic objectForKey:kOrganization] forKey:@"publish"];
    [CheckParams setObject:[_affairsDic objectForKey:kDate] forKey:@"time"];
    if (picsUrlString) {
        [CheckParams setObject:picsUrlString forKey:@"pics"];
    }else{
        [CheckParams setObject:@"http://1.jpg" forKey:@"pics"];
    }
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"op_cwgkpublish.php" httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
        if (str) {
//            [picHud hide:YES];
            [Config showHUDWithText:@"发送失败" andImage:@"error"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
//            [picHud hide:YES];
            [Config showHUDWithText:@"发送成功" andImage:@"done"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }failureAction:^{
        
    }];

//    NSLog(@"title:%@, object:%@, content:%@, organization:%@, date:%@", _affairsDic[kTitle], _affairsDic[kObject], _affairsDic[kContent], _affairsDic[kOrganization], _affairsDic[kDate]);
    
}

-(void)uploadPics{
    
    MBProgressHUD *picHud= [Config createHUD];
    picHud.mode = 0;
    picHud.labelText = @"上传图片中...";
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    NSMutableDictionary *file=[[NSMutableDictionary alloc]init];
    [file setValue:imgDataArray forKey:@"image[]"];
    [MyDataService requestURL:@"upfile_imgs.php" httpMethod:@"POST" params:CheckParams fileDatas:file complection:^(id result) {
        
        NSData *data=result;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@", dic);
        NSDictionary *dataDic=[dic objectForKey:@"date"];
        NSArray *picArray=[[NSArray alloc]initWithArray:[dataDic objectForKey:@"pics"]];
        
        [picHud hide:YES];
        if (!picArray.count==imgDataArray.count) {
            [Config showHUDWithText:@"图片上传失败" andImage:@"error"];
            return ;
        }
        
        for (int i=0; i<picArray.count; i++) {
            
            if (i==0) {
                NSString *picUrlString=[NSString stringWithFormat:@"%@",[picArray objectAtIndex:i]];
                picsUrlString = [NSMutableString stringWithString:picUrlString];
            }else{
                NSString *picUrlString=[NSString stringWithFormat:@",%@",[picArray objectAtIndex:i]];
                picsUrlString=[NSMutableString stringWithFormat:@"%@%@",picsUrlString,picUrlString];
            }
        }
        NSLog(@">>>>>>>>>>>>%@",picsUrlString);
        [self sendContent];
    }failureAction:^{
        [picHud hide:YES];
    }];
}

@end
